package com.munhrasoft.elearning.managedbeans;

import java.io.IOException;
import java.security.Principal;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.munhrasoft.elearning.business.entities.Students;
import com.munhrasoft.elearning.business.logic.StudentsEJB;

@ManagedBean
@SessionScoped
public class LoginController {

    private static Logger logger = Logger.getLogger(LoginController.class.getName());

    @EJB
    private StudentsEJB   studentsEJB;
    private Students      student;
    private String        username;
    private String        password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Students getStudent() {
        return student;
    }

    public void setStudent(Students student) {
        this.student = student;
    }

    public void logout(ActionEvent actionEvent) {
        logger.info("Logout");

        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
                .getSession(false);
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest();

        logger.info("User ({0}) loging out #" + request.getUserPrincipal().getName());

        if (session != null) {
            session.invalidate();
        }
        FacesContext
                .getCurrentInstance()
                .getApplication()
                .getNavigationHandler()
                .handleNavigation(FacesContext.getCurrentInstance(), null,
                        "/loginPage.xhtml?faces-redirect=true");

    }

    public void login(ActionEvent actionEvent) {
        logger.info("Login com validacao");

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        try {
            String navigateString = "";
            // Checks if username and password are valid if not throws a ServletException
            logger.info("username " + username);
            logger.info("password " + password);

            request.login(username, password);
            // gets the user principle and navigates to the appropriate page
            Principal principal = request.getUserPrincipal();
            
            if (request.isUserInRole("administrators")) {
                navigateString = "/administratorMainPage.jsf";
            } else if (request.isUserInRole("students")) {
                navigateString = "/studentMainPage.jsf";
                student = studentsEJB.findAllStudents().get(0);
            }
            try {
                logger.info("User ({0}) loging in #" + request.getUserPrincipal().getName());
                context.getExternalContext().redirect(request.getContextPath() + navigateString);
            } catch (IOException ex) {
                logger.info("IOException, Login Controller" + "Username : " + principal.getName()
                        + ex);
            }
        } catch (ServletException e) {

            e.printStackTrace();

            logger.info("IOException, Login Controller: The username or password you "
                    + "provided does not match our records.");
            context.addMessage(null, new FacesMessage("Error!",
                    "The username or password you provided does not match our records."));
        }

    }

    public String noValidLogin() {
        // just a mock login method, it will be need to use JAAS
        // in the future
        student = studentsEJB.findAllStudents().get(0);
        return "loginok";
    }

}
